<template>
  <div>
    <h2>{{ title }}</h2>
    <p>count:{{ count }}</p>
    <button @click="addCount">Add count</button>

    <br />

    <input type="text" @input="changeCount" ref="el" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
// interface Props {
//   title?: string;
//   count: number;
// }

// defineProps<Props>({
//     title: {
//       type: String,
//       default:'计算'
//     },
//     count: {
//       type: Number,
//       default: 0,
//       required: true,
//     },

// });
// const props = withDefaults(defineProps<Props>(), {
//   title: "计算",
// });

// const changeCount = (e: Event) => {
//   let n = parseInt((e.target as HTMLInputElement).value);
//   if (isNaN(n)) {
//     n = 0;
//   }
//   emit("update:count", n);
// };

// const addCount = () => {
//   emit("update:count", props.count + 1);
// };

// 类似于vue2的.sync 语法糖

// defineEmits(['change']);
// const emit = defineEmits<{
//   (e: "change", n: number): void;
// }>();

// const emit = defineEmits<{
//    "update:count": [id:number];
// }>();

// vue3.4 新的宏命令

const count = defineModel("count", { type: Number, required: true });
const title = defineModel("title", { type: String, default: "计数器" });
const changeCount = (e: Event) => {
  let n = parseInt((e.target as HTMLInputElement).value);
  if (isNaN(n)) {
    n = 0;
  }
  count.value = n;
};
const el = ref<HTMLInputElement | null>(null);
onMounted(() => {
  el.value?.focus();
});

const addCount = () => {
  count.value++;
};
</script>

<style scoped></style>
